package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.UserIdThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends BaseServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FastDFSClient fastDFSClient;

    @Value("${file.url}")
    String fileServerUrl;

    @Autowired
    private WmNewsMaterialMapper materialManageMapper;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        if (multipartFile == null) return paramInvalid;

        Integer userId = UserIdThreadLocalUtils.getUserId();
        if (userId==null)return needLogin;
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(multipartFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(userId);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setType((short) 0);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setUrl(fileId);
        save(wmMaterial);

        wmMaterial.setUrl(fileServerUrl+fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //2.带条件分页查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取当前登录的用户
        Integer uid = UserIdThreadLocalUtils.getUserId();
        if (uid == null) return needLogin;

        lambdaQueryWrapper.eq(WmMaterial::getUserId, uid);
        //是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //按照日期倒序排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        System.out.println(lambdaQueryWrapper.getExpression().getOrderBy());

        IPage pageParam = new Page(dto.getPage(),dto.getSize());
        IPage resultPage = page(pageParam, lambdaQueryWrapper);
        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) resultPage.getTotal());
        List<WmMaterial> datas = resultPage.getRecords();
        //为每个图片加上前缀


//        datas.forEach(w->w.setUrl(fileServerUrl+w.getUrl()));

        datas = datas.stream().map(item -> {
            item.setUrl(fileServerUrl + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(datas);

        return responseResult;
    }


    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null)return errorParam;
        WmMaterial material = getById(id);
        if (material == null)return 图片不存在;
        Integer integer = materialManageMapper.selectCount(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getMaterialId, id));
        if (integer > 0)return PageResponseResult.errorResult(1000,"该图片被引用，无法删除");
        //删除服务器图片
        try {
            fastDFSClient.delFile(material.getUrl().replace(fileServerUrl, ""));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.DELETE_FAILED);
        }
        //删除数据库数据
        removeById(id);

        return ResponseResult.okResult(success);
    }

    @Override
    public ResponseResult updateStatus(Integer id) {
        if (id ==null )return errorParam;
        Integer userId = UserIdThreadLocalUtils.getUserId();
        if (userId == null)return needLogin;
        WmMaterial material = getById(id);
        if (material == null)return 图片不存在;
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,
                (short) (material.getIsCollection()==0?1:0)).eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId));
        return ResponseResult.okResult(success);
    }




}
